﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using WYJCore;
using WYJCore.Extension;
using WYJCore.Web;
using WYJWeb.Models;

namespace WYJWeb.Apis
{
    public class UserController : ControllerBase<User>
    {
        private string sid;
        public override string BaseWhere(string key)
        {
            return "LoginId".Like(key);
        }

        public Response GetList(string key, int pageIndex, int pageSize, string LoginId, string Password)
        {
            return Respond(db =>
            {
                var where = BaseWhere(key);
                return db.GetPageList<User>(pageIndex, pageSize, where);
            });
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public Response Login(string form)
        {
            return Respond(db => {
                var o = JsonConvert.DeserializeObject<User>(form);
                var user = db.GetModel<User>(x => x.LoginId == o.LoginId);
                if (user is null) throw new WYJException("账号不存在");
                if (user.IsDisable) throw new WYJException("账号已禁用");
                if (user.Password != o.Password) throw new WYJException("密码错误");
                CurrentHttpContext.Request.Cookies.TryGetValue("sid", out sid);
                Session.AddUser(sid,user);
                return user;
            });


        }



        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public Response Logout()
        {
            return Respond(db =>
            {
                CurrentHttpContext.Request.Cookies.TryGetValue("sid", out sid);
                Session.currentUsers.RemoveAll(x => x.Id.EqualTo(sid));
            });

        }

        //////////////       
        [HttpPost]
        public Response GetMenus(string form)
        {
            return Respond(db =>
            {
                var list = JsonConvert.DeserializeObject<List<int>>(form);
                return list.Select(i => ConsoleCenter.Menus.Find(m => m.NodeId == i));
            });
        }
    }
}
